package com.morizhang.merchanmanager.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.morizhang.merchanmanager.api.bean.ErrorDefinition;
import com.morizhang.merchanmanager.api.bean.ErrorDefinitionHolder;
import com.morizhang.merchanmanager.api.bean.MerChanManagerException;
import com.morizhang.merchanmanager.api.dao.UserDao;
import com.morizhang.merchanmanager.api.model.UserModel;
import com.morizhang.merchanmanager.api.utils.ErrorUtils;
import com.morizhang.merchanmanager.api.utils.UserSystemAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
public class IdentifyController {
    @Autowired
    UserDao userDao;

    @RequestMapping("/identify")
    public ResponseEntity<Object> identify(HttpSession session, HttpServletRequest request, @RequestBody String requestParams) {
        JSONObject requestParamsJSON = JSON.parseObject(requestParams);
        //HttpSession session = request.getSession();
        HttpHeaders headers;
        JSONObject responseData;
        try {
            switch (requestParamsJSON.getString("requestService")) {
                case "login" -> {
                    JSONObject userInfo = requestParamsJSON.getJSONObject("data");
                    if (userInfo.getString("userID") == null)
                        userInfo.put("userID", "1");
                    JSONObject requestJSON = new JSONObject();
                    requestJSON.put("requestService", "IdentifyCheck");
                    requestJSON.put("requestMethod", "");
                    requestJSON.put("data", userInfo);
                    JSONObject checkResult;
                    try {
                        checkResult = UserSystemAgent.callUserSystemService(requestJSON);
                    } catch (IOException e) {
                        MerChanManagerException exception = new MerChanManagerException();
                        ErrorDefinition error = ErrorDefinitionHolder.get("CANNOT_CONNECT_USER_SYSTEM");
                        exception.setErrorDefinition(error);
                        throw exception;
                    }
                    String checkResultData = checkResult.getString("data");
                    boolean loginIsSuccess = false;
                    try {
                        loginIsSuccess = Boolean.parseBoolean(checkResultData);
                    } catch (Exception e) {
                        MerChanManagerException exception = new MerChanManagerException();
                        ErrorDefinition error = new ErrorDefinition(JSONObject.parseObject(checkResultData));
                        exception.setErrorDefinition(error);
                        throw exception;
                    }
                    //登录失败,用户名或密码错误
                    if (!loginIsSuccess) {
                        MerChanManagerException exception = new MerChanManagerException();
                        ErrorDefinition error = ErrorDefinitionHolder.get("WRONG_PASSWORD");
                        exception.setErrorDefinition(error);
                        throw exception;
                    }
                    //登录成功, 查询用户信息并写入session
                    requestJSON = new JSONObject();
                    requestJSON.put("requestService", "QueryUserInfo");
                    requestJSON.put("requestMethod", "selectUserByUserName");
                    requestJSON.put("data", userInfo);
                    JSONObject userInfoSearchResult;
                    try {
                        userInfoSearchResult = UserSystemAgent.callUserSystemService(requestJSON);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    JSONObject userInfoSearchResultJSON = userInfoSearchResult.getJSONArray("data").getJSONObject(0);
                    UserModel userInfoLocalDBSearchResult = userDao.queryUserInfoByUserID(userInfoSearchResultJSON.getString("UserID"));
                    if (userInfoLocalDBSearchResult == null) {
                        MerChanManagerException exception = new MerChanManagerException();
                        ErrorDefinition error = ErrorDefinitionHolder.get("USER_NOT_EXIST_IN_CURRENT_SYSTEM");
                        exception.setErrorDefinition(error);
                        throw exception;
                    }
                    String userRole = userInfoLocalDBSearchResult.getUserRole();
                    UserModel roleInfo = userDao.queryRoleInfoByUserRole(userRole);
                    if (roleInfo == null) {
                        MerChanManagerException exception = new MerChanManagerException();
                        ErrorDefinition error = ErrorDefinitionHolder.get("REQUEST_USER_DOESNT_BELONG_ANY_ROLE");
                        exception.setErrorDefinition(error);
                        throw exception;
                    }
                    //设置session
                    session.setAttribute("userRole", roleInfo.getUserRole());
                    session.setAttribute("roleName", roleInfo.getRoleName());
                    session.setAttribute("roleComment", roleInfo.getRoleComment());
                    session.setAttribute("userID", userInfoSearchResultJSON.getString("UserID"));
                    session.setAttribute("userName", userInfoSearchResultJSON.getString("UserName"));
                    session.setAttribute("userComment", roleInfo.getUserComment());
                    userInfoSearchResultJSON.remove("password");
                    headers = new HttpHeaders();
                    headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
                    responseData = new JSONObject();
                    responseData.put("isSuccess", "success");
                    responseData.put("data", userInfoSearchResultJSON);
                    return new ResponseEntity<>(responseData, headers, HttpStatus.OK);
                }
                case "getNowUserInfo" -> {
                    session = request.getSession();
                    String userID = (String)session.getAttribute("userID");
                    String userName = (String)session.getAttribute("userName");
                    String userRole = (String)session.getAttribute("userRole");
                    String roleName = (String)session.getAttribute("roleName");
                    String roleComment = (String)session.getAttribute("roleComment");
                    String userComment = (String)session.getAttribute("userComment");
                    if (userID == null || userName ==null || userRole == null || roleName == null) {
                        session.invalidate();
                        MerChanManagerException exception = new MerChanManagerException();
                        ErrorDefinition error = ErrorDefinitionHolder.get("NOW_USER_INFO_INCOMPLETE");
                        exception.setErrorDefinition(error);
                        throw exception;
                    }
                    headers = new HttpHeaders();
                    headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
                    responseData = new JSONObject();
                    responseData.put("isSuccess", "success");
                    JSONObject data = new JSONObject();
                    data.put("userID", userID);
                    data.put("userName", userName);
                    data.put("userRole", userRole);
                    data.put("roleName", roleName);
                    data.put("roleComment", roleComment);
                    data.put("userComment", userComment);
                    responseData.put("data", data);
                    return new ResponseEntity<>(responseData, headers, HttpStatus.OK);
                }
                case "logout" -> {
                    session = request.getSession();
                    session.invalidate();
                    headers = new HttpHeaders();
                    headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
                    responseData = new JSONObject();
                    responseData.put("isSuccess", "success");
                    return new ResponseEntity<Object>(responseData, headers, HttpStatus.OK);
                }
                default -> {
                    MerChanManagerException exception = new MerChanManagerException();
                    ErrorDefinition error = ErrorDefinitionHolder.get("USER_SYSTEM_REQUEST_SERVICE_NOT_EXIST");
                    exception.setErrorDefinition(error);
                    throw exception;
                }
            }
        } catch (MerChanManagerException merChanManagerException) {
            ErrorDefinition error = merChanManagerException.getErrorDefinition();
            responseData = ErrorUtils.convertErrorToJsonForm(error);
            responseData.put("isSuccess", "fail");
            headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            return new ResponseEntity<Object>(responseData, headers, HttpStatus.BAD_REQUEST);
        }
    }

}
